<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>磁性摆动链接效果</title>
    <style>
        body {
            display: flex;
            justify-content: center;
            align-items: center;
            height: 100vh;
            margin: 0;
            font-family: Arial, sans-serif;
        }
        
        .magnetic-link {
            display: inline-block;
            padding: 15px 30px;
            background-color: #f0f0f0;
            color: #333;
            text-decoration: none;
            border-radius: 30px;
            font-weight: bold;
            transition: 
                background-color 0.3s ease,
                transform 0.2s ease-out;
            position: relative;
        }
        
        .magnetic-link:hover {
            background-color: #4CAF50;
            color: white;
        }
    </style>
</head>
<body>
    <a href="#" class="magnetic-link">悬停试试</a>

    <script>
        const link = document.querySelector('.magnetic-link');
        
        link.addEventListener('mousemove', (e) => {
            // 获取鼠标在元素内的相对位置 (0-1)
            const x = e.offsetX / link.offsetWidth;
            
            // 计算摆动幅度 (-10px 到 10px)
            const swing = (x - 0.5) * 20;
            
            // 应用摆动效果
            link.style.transform = `translateX(${swing}px)`;
        });
        
        link.addEventListener('mouseleave', () => {
            // 鼠标离开时恢复原状
            link.style.transform = 'translateX(0)';
        });
    </script>
</body>
</html>
